package com.liruo.demo.serialize.jackson.factory;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.liruo.demo.serialize.jackson.model.User;
import java.io.IOException;

/**
 * @Author:liruo
 * @Date:2023-02-20-02:38:43
 * @Desc
 */
public class MyDeserializerFactory extends JsonDeserializer<User> implements
    ContextualDeserializer {

  private String prefix = "";
  private Class clazz;

  public MyDeserializerFactory() {
  }

  public MyDeserializerFactory(String prefix, Class clazz) {
    this.prefix = prefix;
    this.clazz = clazz;
  }

  @Override
  public JsonDeserializer<User> createContextual(DeserializationContext deserializationContext,
      BeanProperty property) throws JsonMappingException {
    String prefix = property.getAnnotation(ValuePrefix.class).prefix();
    JavaType type = property.getType();

    if (type.isTypeOrSubTypeOf(User.class)) {
      return new MyDeserializerFactory(prefix, User.class);
    }
    throw new RuntimeException("不支持的类型,  仅支持 String, Collection");
  }

  @Override
  public Class<?> handledType() {
    return clazz;
  }

  @Override
  public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
      throws IOException, JacksonException {
    JavaType contextualType = deserializationContext.getContextualType();

    System.out.println(contextualType);

    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode root = mapper.readTree(jsonParser);
    String name = root.get("name").asText();

    if (name.startsWith(MyDeserializerFactory.this.prefix)) {
      name = name.substring(MyDeserializerFactory.this.prefix.length());
    }

    String des = root.get("des").asText();
    if (des.startsWith(MyDeserializerFactory.this.prefix)) {
      des = des.substring(MyDeserializerFactory.this.prefix.length());
    }

    return new User(name, des);
  }

}
